//
//  ViewController.m
//  IPTest
//
//  Created by sank zhang on 2018/12/17.
//  Copyright © 2018年 sank zhang. All rights reserved.
//  9.3.2

#import "ViewController.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#import "PersonModel.h"

@interface ViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    [self getIPWithHostName:@"www.baidu.com"];
//    [self getIPWithHostName:@"api.ahmobile.cn"];
//
//    [self getNetworkType];
//    [self testPersonModel];
//    [self.view addSubview:self.imageView];
//    UIImage *image = [self generateBarCode:@"2134123 41234 234123" size:CGSizeMake(self.view.frame.size.width * .6, 60) color:[UIColor blackColor] backGroundColor:[UIColor whiteColor]];
//    self.imageView.image = image;
    
//    [self testMaopao];
    
//    https://api.ahmobile.cn/eip?eip_serv_id=app.h5_familyPlanIndex&phoneOpen=DiangjQ+b+uqUi0Va4do+JjqCGKzsFHICoRIEE3ZMOPyB/+mLWuRSt8fXAutffDDcMF/+RaY8O3Feyx+cU5r1RuOeqiOfWdFhqdl4RVYxijCaQ4gSgYuVSz883delcGCV+UxxexWHUW2bZIcLVn2aPzIW9/oCzg8hXH4hfF0acQ=
//%2B
//    https://api.ahmobile.cn/eip?eip_serv_id=app.h5_familyPlanIndex&phoneOpen=DiangjQ+b+uqUi0Va4do+JjqCGKzsFHICoRIEE3ZMOPyB/+mLWuRSt8fXAutffDDcMF/+RaY8O3Feyx+cU5r1RuOeqiOfWdFhqdl4RVYxijCaQ4gSgYuVSz883delcGCV+UxxexWHUW2bZIcLVn2aPzIW9/oCzg8hXH4hfF0acQ=
    
//    https://api.ahmobile.cn/eip?eip_serv_id=app.h5_familyPlanIndex&phoneOpen=DiangjQ%2Bb%2BuqUi0Va4do%2BJjqCGKzsFHICoRIEE3ZMOPyB/%2BmLWuRSt8fXAutffDDcMF/%2BRaY8O3Feyx%2BcU5r1RuOeqiOfWdFhqdl4RVYxijCaQ4gSgYuVSz883delcGCV%2BUxxexWHUW2bZIcLVn2aPzIW9/oCzg8hXH4hfF0acQ=
    NSString *testUrl = @"https://api.ahmobile.cn/eip?eip_serv_id=app.h5_familyPlanIndex&phoneOpen=";
    NSString *encodeParam = [self nt_encodeURL:@"DiangjQ+b+uqUi0Va4do+JjqCGKzsFHICoRIEE3ZMOPyB/+mLWuRSt8fXAutffDDcMF/+RaY8O3Feyx+cU5r1RuOeqiOfWdFhqdl4RVYxijCaQ4gSgYuVSz883delcGCV+UxxexWHUW2bZIcLVn2aPzIW9/oCzg8hXH4hfF0acQ="];
    NSString *encodeUrl = [NSString stringWithFormat:@"%@%@",testUrl,encodeParam];
    BOOL isabc = [self checkURL:encodeUrl];;
    NSLog(@"------:%@\n-------:%d",encodeUrl,isabc);
}


//- (void)getImageTextWithParams:(NSDictionary *)params callBack:(void (^)(NSMutableAttributedString *imageAtbs))callBack
//{
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        UIImage *image = params[@"image"];
//        image = [UIImage imageWithCGImage:image.CGImage scale:2 orientation:image.imageOrientation];
//        image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:0];
//
//        NSString *text = params[@"text"];
//        CGFloat imageToTextSpace = [params[@"space"] floatValue];
//        CGFloat containerHegiht = [params[@"height"] floatValue];
//        UIFont *textFont = params[@"font"];
//        UIColor *textColor = params[@"color"];
//
//        NSDictionary *textAttributedDict = @{
//                                             NSFontAttributeName: textFont,
//                                             NSForegroundColorAttributeName: textColor
//                                             };
//
//        CGSize textSize =  [text sizeWithAttributes:textAttributedDict];
//
//        CGSize imageSize = CGSizeMake(textSize.width + imageToTextSpace * 2, MIN(containerHegiht, textFont.lineHeight + 4));
//
//        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
//        [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
//
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        CGContextDrawPath(context, kCGPathStroke);
//
//        [text drawInRect:CGRectMake(imageToTextSpace, (containerHegiht - textFont.lineHeight) * 0.5, textSize.width, textFont.lineHeight) withAttributes:textAttributedDict];
//
//        UIImage *contentImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//
//        NSMutableAttributedString *imageAtbs = [NSMutableAttributedString yy_attachmentStringWithContent:contentImage contentMode:UIViewContentModeCenter attachmentSize:imageSize alignToFont:textFont alignment:YYTextVerticalAlignmentCenter];
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (callBack) {
//                callBack(imageAtbs);
//            }
//        });
//    });
//}

- (BOOL)checkURL:(NSString *)url
{
    NSString *urlRegex = @"((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    return [urlTest evaluateWithObject:url];
}

- (void)testMaopao
{
    NSMutableArray *paopaoArray = [[NSMutableArray alloc] initWithArray:@[@1,@3,@4,@5,@2,@3,@4,@5,@6,@7,@7,@8,@8,@9,@9,@3,@2,@1,@3,@4,@5,@6,@4]];
    NSInteger count = paopaoArray.count;
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < count - 1 - i; j++) {
            NSNumber *num1 = paopaoArray[j];
            NSNumber *num2 = paopaoArray[j + 1];
            if ([num1 integerValue]> [num2 integerValue]) {
                [paopaoArray replaceObjectAtIndex:j withObject:num2];
                [paopaoArray replaceObjectAtIndex:j + 1 withObject:num1];
            }
        }
    }
    for (int i = 0; i < count; i++) {
        NSLog(@"%@,",paopaoArray[i]);
    }
}

- (NSString *)nt_encodeURL:(NSString *)url
{
    NSString *newString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)url, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    if (newString) {
        return newString;
    }
    return @"";
}


- (void)testPersonModel
{
    PersonModel *ps = [[PersonModel alloc] init];
    ps.userName = @"梧雨北辰";
    ps.age  = 18;
    NSString *temp = NSTemporaryDirectory();
    NSString *fileTemp = [temp stringByAppendingString:@"person.archive"];
    [NSKeyedArchiver archiveRootObject:ps toFile:fileTemp];
    
    //--测试解档
    NSString *temp1 = NSTemporaryDirectory();
    NSString *fileTemp1 = [temp1 stringByAppendingString:@"person.archive"];
    PersonModel *person = [NSKeyedUnarchiver unarchiveObjectWithFile:fileTemp1];
    NSLog(@"person-name:%@，person-age:%ld",person.userName,person.age);
}


- (NSString*)getIPWithHostName:(const NSString*)hostName {
    const char *hostN= [hostName UTF8String];
    struct hostent* phot;
    @try {
        phot = gethostbyname(hostN);
    } @catch (NSException *exception) {
        return nil;
    }
    struct in_addr ip_addr;
    if (phot == NULL) {
        NSLog(@"获取失败");
        return nil;
    }
    memcpy(&ip_addr, phot->h_addr_list[0], 4);
    char ip[20] = {0}; inet_ntop(AF_INET, &ip_addr, ip, sizeof(ip));
    NSString* strIPAddress = [NSString stringWithUTF8String:ip];
    NSLog(@"ip=====%@",strIPAddress);
    return strIPAddress;
}

- (NSString *)getNetworkType
{
    UIApplication *app = [UIApplication sharedApplication];
    id statusBar = [app valueForKeyPath:@"statusBar"];
    NSString *network = @"";
    
    if (WXOSIPhoneX()) {
        //        iPhone X
        id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
        UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
        
        NSArray *subviews = [[foregroundView subviews][2] subviews];
        
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                network = @"WIFI";
            }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
                network = [subview valueForKeyPath:@"originalText"];
            }
        }
    }else {
        //        非 iPhone X
        UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
        NSArray *subviews = [foregroundView subviews];
        
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
                switch (networkType) {
                    case 0:
                        network = @"NONE";
                        break;
                    case 1:
                        network = @"2G";
                        break;
                    case 2:
                        network = @"3G";
                        break;
                    case 3:
                        network = @"4G";
                        break;
                    case 5:
                        network = @"WIFI";
                        break;
                    default:
                        break;
                }
            }
        }
    }
    if ([network isEqualToString:@""]) {
        network = @"没有网络";
    }
    NSLog(@"------:%@",network);
    return network;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

BOOL WXOSIPhoneX()
{   //
    //    return [UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size)) : NO;
    static dispatch_once_t onceToken;
    static  BOOL isIPhoneX = NO;
    dispatch_once(&onceToken, ^{
        //        isIPhoneX = [UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size)) : NO;
        isIPhoneX = WXOSIPhoneXSafeArea();
    });
    return  isIPhoneX;
    
}
BOOL WXOSIPhoneXSafeArea()
{
    if (@available(iOS 11.0, *)) {
        UIWindow *window = [[[UIApplication sharedApplication] delegate]window];
        if (window.safeAreaInsets.bottom > 0.0) {
            return YES;
        } else {
            return NO;
        }
    }else{
        return NO;
    }
}

- (UIImageView *)imageView
{
    if (_imageView == nil) {
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = CGRectMake(0, 200, self.view.frame.size.width, 100);
    }
    return _imageView;
}

//条形码生成
- (UIImage *)generateBarCode:(NSString *)code size:(CGSize)size color:(UIColor *)color backGroundColor:(UIColor *)backGroundColor
{
    // 生成条形码图片
    CIImage *barcodeImage;
    NSData *data = [code dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
    CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    //设置条形码颜色和背景颜色
    CIFilter * colorFilter = [CIFilter filterWithName:@"CIFalseColor"];
    [colorFilter setValue:filter.outputImage forKey:@"inputImage"];
    //条形码颜色
    if (color == nil) {
        color = [UIColor blackColor];
    }
    if (backGroundColor == nil) {
        backGroundColor = [UIColor whiteColor];
    }
    [colorFilter setValue:[CIColor colorWithCGColor:color.CGColor] forKey:@"inputColor0"];
    //背景颜色
    [colorFilter setValue:[CIColor colorWithCGColor:backGroundColor.CGColor] forKey:@"inputColor1"];
    
    barcodeImage = [colorFilter outputImage];
    
    // 消除模糊
    CGFloat scaleX = size.width / barcodeImage.extent.size.width; // extent 返回图片的frame
    CGFloat scaleY = size.height / barcodeImage.extent.size.height;
    CIImage *transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
    
    return [UIImage imageWithCIImage:transformedImage];
}
@end
